package com.ts.shiro;

import com.ts.login.bean.PostInfo;
import com.ts.login.bean.UserInfo;
import com.ts.login.dao.LoginDao;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xhc on 2017/3/27.
 */
public class TsRealm extends AuthorizingRealm {


    Logger log=Logger.getLogger(TsRealm.class);
    @Resource
    private LoginDao loginDao;
    /**
     * 权限管理
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String username = (String) getAvailablePrincipal(principalCollection);
        try {
            UserInfo u = loginDao.getUser(username);
            if(u!=null){
                SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
                //设置用户的角色
                info.setRoles(u.getRoles());
                //设置用户模块权限
                List<PostInfo> posts = u.getUserPosts();
                //设置模块权限
                List<String> userPosts=new ArrayList<String>();
                if(posts!=null && !posts.isEmpty()){
                    for(PostInfo p :posts){
                        userPosts.add(p.getCode());
                    }
                }
                List<String> pers = loginDao.getPostModels(userPosts);
                info.addStringPermissions(pers);
                return info;
            }
        } catch (Exception e) {
            log.error("shiro授权失败:"+e.getLocalizedMessage());
        }
        return null;
    }

    /**
     * 用户登录验证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        //从数据库中拿到密码
        String password="";
        UserInfo u = null;
        try {
            u = loginDao.getUser(username);
            if(u==null){
                throw new UnknownAccountException("账号或密码不正确");
            }
            //数据密码保护冒号，需要剔除
            password=u.getPassword().replace(":", "").toLowerCase();
        } catch (Exception e) {
            log.error("shiro登录失败："+e.getLocalizedMessage());
            throw new UnknownAccountException(e.getLocalizedMessage());
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());
        return info;
    }

    public static void main(String[] args) {
        String hashAlgorithmName = "MD5";
        Object credentials = "1";
        Object salt = "";//ByteSource.Util.bytes("user");//盐值
        int hashIterations = 1;
        //c4ca4238a0b923820dcc509a6f75849b
        Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
        System.out.println(result);
    }
}
